package com.begye.smartloan.apptest.jujue

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import com.begye.smartloan.apptest.tool.IApiProcessCallback
import com.begye.smartloan.apptest.tool.doPostRequest
import org.json.JSONArray
import org.json.JSONObject

class JuJueViewModel : ViewModel() {

    private val _loadingStateLiveData = MutableLiveData<Boolean>()
    val onLoadingStateLiveData get() = _loadingStateLiveData

    private val _juJueProductListLiveData = MutableLiveData<List<JSONObject>>()
    val onJuJueProductListLiveData get() = _juJueProductListLiveData

    fun requestJuJueProductList() {
        doPostRequest(
            path = "/yyBqRRPEqmxRNEv1MjY9lQ",
            action = hashMapOf(),
            loading = _loadingStateLiveData,
            callback = object : IApiProcessCallback {
                override fun onApiReady() {
                }

                override fun onApiDone(jsonObject: JSONObject) {
                    try {
                        val obj = jsonObject.optJSONObject("obj") ?: JSONObject()

                        val array = obj.optJSONArray("dcProductList") ?: JSONArray()

                        val list = mutableListOf<JSONObject>()
                        for (index in 0 until array.length()) {
                            val item = array.optJSONObject(index)
                            if (item != null) {
                                list.add(item)
                            }
                        }
                        _juJueProductListLiveData.value = list

                    } catch (e: Exception) {
                        //
                    }
                }

                override fun onApiError(code: String, errMsg: String) {
                }

            })
    }
}